#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Text;

namespace Osh.Configuration
{
	public interface IEpgElement : IConfigurationElement
	{
		bool Enabled { get; set; }
		string PreferredLanguages { get; set; }
	}

	[ClassInterface(ClassInterfaceType.None)]
	public class EpgElement : ConfigurationElement, IEpgElement
	{
		private static char[] LanguageSeparators = new char[] { ',' };
		private List<string> _preferredLanguages;

		public EpgElement()
		{
		}

		[ConfigurationProperty("enabled")]
		public bool Enabled
		{
			get { return (bool)this["enabled"]; }
			set { this["enabled"] = value; }
		}

		/// <summary>
		/// Comma separated list of preferred languages.
		/// If EPG records contain information on more the one language,
		/// this property specify which languages should be used first.
		/// </summary>
		[ConfigurationProperty("preferredLanguages", DefaultValue = "eng")]
		public string PreferredLanguages
		{
			get { return (string)this["preferredLanguages"]; }
			set
			{
				this["preferredLanguages"] = value;
				_preferredLanguages = null;
			}
		}
		 
		public bool IsLanguageMorePrefered(string language, string thanLanguage)
		{
			int firstLangIndex = this.PreferredLanguages.IndexOf(language);
			if(firstLangIndex == -1) return false;

			int secondLangIndex = this.PreferredLanguages.IndexOf(thanLanguage);
			if(secondLangIndex == -1) return true;

			return firstLangIndex < secondLangIndex;
		}

		private List<string> PreferredLanguageList
		{
			get
			{
				if(_preferredLanguages == null)
				{
                    string preferredLanguagesStr = this.PreferredLanguages;
					if(preferredLanguagesStr != null)
					{
						preferredLanguagesStr = preferredLanguagesStr.Replace(" ", "");
						_preferredLanguages = new List<string>(
							preferredLanguagesStr.Split(LanguageSeparators, StringSplitOptions.RemoveEmptyEntries));
					}
					else
						_preferredLanguages = new List<string>();
				}
				return _preferredLanguages;
			}
		}

	}
}
